<script>
import {
  Delete_incoming_and_outgoing_records,
  Query_incoming_and_outgoing_records,
  Add_incoming_and_outgoing_records,
  uploadUrl
} from "@/api"
import axios from "axios";
import moment from "moment";

export default {
  name: "stockRecord",
  data() {
    return {
      uploadUrl,
      paramsState: {
        date: [],
        startpoint: 1,
        nums: 10
      },
      findData: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      tableData: [],
      listLoading: false,
      Visible: false,
      fileList: [],
      multipleSelection: []
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 表格选择事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    downloadList() {
      const length = this.multipleSelection.length;
      if (length <= 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }

      this.$confirm(`确定要下载选中的${length}条数据吗`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.multipleSelection.forEach(item => {
          this.download(item.file_url);
        })
      })
    },
    async uploadChunk(option, option2) {
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      console.log(option, option2)
      const formData = new FormData();
      formData.append('total', option2.totalPages);
      formData.append('index', option2.index);
      formData.append('mainway', 'xls');
      formData.append('filename', option2.filename);
      formData.append('data', option.chunk);

      // 使用Axios或其他HTTP库发送请求
      await axios.post(uploadUrl, formData, {
        headers: {'Content-Type': 'multipart/form-data'}
      })
          .then(response => {
            console.log(option2.index + '：分片上传成功:', response);
            if (option2.index == option2.totalPages) {
              console.log('分片上传结束:', response);
              // response.data.path
              this.fileList = [];
              Add_incoming_and_outgoing_records({
                generate_time: moment().format(`YYYY-MM-DD HH:mm:ss`),
                file_url: response.data.path
              }).then(res => {
                this.$message.success("上传成功")
                this.getList()
                loading.close();
              }).catch(() => {
                loading.close();
              })
            }
          })
          .catch(error => {
            loading.close();
            console.error('分片上传失败:', error);
          });
    },
    onRequest(a, b, c) {
      console.log(a.file);
      let _this = this;
      this.fileList = [];
      const file = a.file;
      const fileSize = file.size;
      const CHUNK_SIZE = 2 * 1024 * 1024; // 每个分片的大小
      let offset = 0;
      let totalPages = Math.ceil(fileSize / CHUNK_SIZE);
      let index = 1;
      let filename = Date.now() + '.xls';

      while (offset < fileSize) {
        const chunkSize = Math.min(CHUNK_SIZE, fileSize - offset);
        const chunk = file.slice(offset, offset + chunkSize);

        _this.uploadChunk({
          chunk, offset, fileSize
        }, {
          filename, totalPages, index
        });
        // _this.uploadChunk(totalPages, index, file,);
        index++;
        offset += chunkSize;
      }

    },
    // 下载单个文件
    download(url) {
      if (!url) return Message.error("无文件下载");
      axios({
        url: url,
        method: 'GET',
        responseType: 'blob', // 设置响应类型为二进制流
      }).then(res => {
        const blob = new Blob([res.data], {type: 'application/octet-stream'});
        const url = window.URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = Date.now() + '.xls';
        a.style.display = 'none';
        document.body.appendChild(a);

        a.click();

        window.URL.revokeObjectURL(url);
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete_incoming_and_outgoing_records({id: row.id}).then(() => {
          this.$message({
            type: 'success', message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    getList() {
      let params = {
        ...this.paramsState,
        starttime: "",
        endtime: "",
      }
      console.log(params)
      if (params.date) {
        if (params.date.length == 2) {
          let [starttime, endtime] = params.date;
          params.starttime = starttime;
          params.endtime = endtime;
        }
      }

      delete params.date;
      Query_incoming_and_outgoing_records(params).then(res => {
        console.log(res)
        this.tableData = res.data
        this.listLoading = false
        this.paramsState.total = res.total;
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 根据用户选择进行查询
    search() {
      this.paramsState.startpoint = 1
      this.getList()
    },
    sizeChange(e) {
      this.paramsState.nums = e
      this.getList()
    },
    currentChange(e) {
      this.paramsState.startpoint = e
      this.getList()
    },
    resetDialog() {
      this.findData = {}
    },
  }
}
</script>

<template>
  <div class="wrapper">
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="7" class="flex">
        <el-date-picker
            class="w100"
            v-model="paramsState.date"
            type="datetimerange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions">
        </el-date-picker>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-search"
                   @click="search">搜索
        </el-button>
      </el-col>
      <el-col :span="12">
        <el-upload
            class="upload-demo"
            action=""
            accept=".xls,.xlsx"
            :limit="1"
            :http-request="onRequest"
            :file-list="fileList">
          <el-button size="small" type="primary">新增记录</el-button>
          <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-download"
                     @click.stop="downloadList">批量下载
          </el-button>
        </el-upload>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table :data="tableData" v-loading="listLoading" border @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          fixed
          align="center"
          width="45">
      </el-table-column>
      <el-table-column prop="generate_time" label="生成时间" align="center"/>
      <el-table-column prop="file_url" label="文件" align="center">
        <template v-slot="{ row }">
          <el-button type="text" title="下载" @click="download(row.file_url)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button type="text" title="删除" style="color:#f46162;" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination :current-page="paramsState.startpoint" :page-size="paramsState.nums" :total="paramsState.total"
                   :page-sizes="[5, 10, 20, 30]" style="padding: 20px 0"
                   layout="prev, pager, next, jumper, ->, sizes, total"
                   @current-change="currentChange" @size-change="sizeChange"/>

    <!-- 查看 or 编辑框-->
    <el-dialog title="查看" width="800px" :visible.sync="Visible" @closed="resetDialog">
      <el-form size="small" class="formRow" label-position="top">
        <el-form-item label="文件" prop="file_url">

        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.wrapper {
  margin: 20px;

  .label {
    font-size: 14px;
    color: #333;
    padding-bottom: 10px;
  }
}
</style>
